package com.honeybee.cloud.framework.common.utils;

import cn.hutool.core.util.NumberUtil;
import com.honeybee.cloud.framework.common.constant.CommonSystemConstant;
import org.springframework.util.StringUtils;

/**
 * @Description 字符处理
 * @Author DELL
 * @Create 2019-04-30
 * @Since 1.0.0
 */
public class StrUtils {

    /**
     * 百分比数转int 小数点后少于已有的时，保留全部小数位
     *
     * @param str
     * @param length 转换后需要的小数位
     * @return
     */
    public static Long convertNumber(String str, int length) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        boolean isContains = false;
        if (str.contains(CommonSystemConstant.HYPHEN)) {
            isContains = true;
        }

        //去掉一些字符串前后不是数字的非字符
        str = str.replace("%", "");
        str = str.replace("+", "");
        str = str.replace("↓", "");
        str = str.replace("↑", "");
        str = str.replaceAll("[^0-9]+$", "");
        str = str.replaceAll("^[^0-9]+", "");

        if (!NumberUtil.isNumber(str)) {
            return null;
        }

        StringBuffer sdf = new StringBuffer();
        int i = str.indexOf(CommonSystemConstant.PERIOD);

        for (char d : str.toCharArray()) {
            if (!String.valueOf(d).equals(CommonSystemConstant.PERIOD)) {
                sdf.append(d);
            }
        }
        int charLength = sdf.length();
        i = i < 0 ? charLength : i;
        for (int j = 0; j < length - (charLength - i); j++) {
            sdf.append(0);
        }
        int floatLength = charLength - i;
        if (i != charLength && floatLength > length) {
            sdf = sdf.delete(sdf.length() - (floatLength - length), sdf.length());
        }
        if (isContains) {
            sdf.insert(0, CommonSystemConstant.HYPHEN);
        }
        return Long.parseLong(sdf.toString());
    }

}
